package app.itgungnir.compose.wan.utils

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import app.itgungnir.compose.wan.WanApp
import app.itgungnir.compose.wan.api.WanDao
import app.itgungnir.compose.wan.business.main.agenda.Agenda
import app.itgungnir.compose.wan.business.main.home.HomeArticle
import app.itgungnir.compose.wan.business.main.home.HomeBanner
import app.itgungnir.compose.wan.business.main.square.Square
import app.itgungnir.compose.wan.business.my_collection.MyCollection
import app.itgungnir.compose.wan.business.my_website.MyWebsite

@Database(
    entities = [
        HomeBanner::class,
        HomeArticle::class,
        MyCollection::class,
        MyWebsite::class,
        Agenda::class,
        Square::class
    ],
    version = 1,
    exportSchema = false
)
abstract class WanDatabase : RoomDatabase() {

    companion object {
        val dao: WanDao by lazy { instance.dao() }
        val instance: WanDatabase by lazy {
            synchronized(this) {
                Room.databaseBuilder(
                    WanApp.instance.applicationContext,
                    WanDatabase::class.java,
                    "wan_compose.db"
                ).build()
            }
        }
    }

    suspend fun onUserLogout() {
        dao.deleteAllMyCollections()
        dao.deleteAllMyWebsites()
        dao.updateAllHomeArticlesUncollected()
        dao.deleteAllAgendas()
        dao.deleteAllSquares()
    }

    abstract fun dao(): WanDao
}
